package com.KA.service.impl;

import com.KA.dto.ConsumeVo;
import com.KA.dto.RefundVo;
import com.KA.entity.UserWallet;
import com.KA.exception.BusinessException;
import com.KA.service.UserWalletService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.KA.dto.AccountDto;
import com.KA.entity.Account;
import com.KA.entity.User;
import com.KA.mapper.AccountMapper;
import com.KA.mapper.UserMapper;
import com.KA.service.AccountService;
import com.KA.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.List;

@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Autowired
    AccountMapper accountMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    private UserWalletService userWalletService;


    @Override
    public Boolean savezj(Account account) {
        //获得当前用户id
        String userId = UserThreadLocal.get().getId();
        //查询用户数据
        User user = userMapper.selectById(userId);
        if(account.getGetorpay()==1){
            //如果是支出，判断钱包金额是否足够
            UserWallet one = userWalletService.getOne(new LambdaQueryWrapper<UserWallet>().eq(UserWallet::getUId,userId));
            ConsumeVo consumeVo = new ConsumeVo();
            consumeVo.setIdCard("1");
            consumeVo.setMobile(user.getPhone());
            consumeVo.setPaymentCode("123456");
            consumeVo.setStatus(1);
            consumeVo.setPayMoney(account.getPrice());
            consumeVo.setUserWalletId(one.getId());
            Boolean consume = userWalletService.consume(consumeVo);
            if(!consume){
                return false;
            }
        }
        account.setUserId(user.getId());
        account.setCreateTime(LocalDateTime.now());
        account.setUpdateTime(LocalDateTime.now());
        return accountMapper.insert(account)>=1;
    }

    @Override
    public List<Account> zlist(AccountDto accountDto) throws ParseException {
        //获取当前登录者的userid
        String id = UserThreadLocal.get().getId();

        LambdaQueryWrapper<Account> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Account::getUserId, id);

        if (!StringUtils.isEmpty(accountDto.getDate())) {
            //格式化前端传过来的时间字符串
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date Date = simpleDateFormat.parse(accountDto.getDate());
            LocalDateTime start = LocalDateTime.of(Date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(), LocalTime.MIN);
            LocalDateTime end = LocalDateTime.of(Date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(), LocalTime.MAX);
            lambdaQueryWrapper.between(Account::getCreateTime, start, end);
        }

        //如果备注不为空，就根据备注查询
        lambdaQueryWrapper.like(accountDto.getMassge() != null, Account::getMassge, accountDto.getMassge());
        lambdaQueryWrapper.orderByDesc(Account::getCreateTime);
        List<Account> accounts = accountMapper.selectList(lambdaQueryWrapper);
        return accounts;
    }

    @Override
    public String accountPay() {
        //获取当前登录者的userid
        String id = UserThreadLocal.get().getId();

        LambdaQueryWrapper<Account> LambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper.eq(Account::getUserId, id);

        LocalDateTime date = LocalDateTime.now();
        LocalDateTime start = date.with(TemporalAdjusters.firstDayOfMonth());
        LocalDateTime end = date.with(TemporalAdjusters.lastDayOfMonth());
        LambdaQueryWrapper.between(Account::getCreateTime, start, end);
        //查找该用户的账单表
        List<Account> accountslist = baseMapper.selectList(LambdaQueryWrapper);

        BigDecimal allpay =  new BigDecimal("0");
       for (int i=0;i<accountslist.size();i++){
           //只有为支出，1，的数据才加入到allpay里
           if(accountslist.get(i).getGetorpay()==1){
               BigDecimal price = accountslist.get(i).getPrice();
               allpay=allpay.add(price);
           }
       }
        return allpay.toString();
    }

    @Override
    public String accountGet() {
        //获取当前登录者的userid
        String id = UserThreadLocal.get().getId();

        LambdaQueryWrapper<Account> LambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper.eq(Account::getUserId, id);

        LocalDateTime date = LocalDateTime.now();
        LocalDateTime start = date.with(TemporalAdjusters.firstDayOfMonth());
        LocalDateTime end = date.with(TemporalAdjusters.lastDayOfMonth());
        LambdaQueryWrapper.between(Account::getCreateTime, start, end);
        //查找该用户的账单表
        List<Account> accountslist = baseMapper.selectList(LambdaQueryWrapper);

        BigDecimal allpay =  new BigDecimal("0");
        for (int i=0;i<accountslist.size();i++){
            //只有为支出，1，的数据才加入到allpay里
            if(accountslist.get(i).getGetorpay()==0){
                BigDecimal price = accountslist.get(i).getPrice();
                allpay=allpay.add(price);
            }
        }
        return allpay.toString();
    }

    @Override
    public Boolean deleteAccount(Long id) {
        Account account = baseMapper.selectById(id);
        UserWallet one = userWalletService.getOne(new LambdaQueryWrapper<UserWallet>().eq(UserWallet::getUId, account.getUserId()));
        RefundVo refundVo = new RefundVo();
        refundVo.setUserWalletId(one.getId());
        refundVo.setStatus(1);
        refundVo.setRefundMoney(account.getPrice());
        Boolean refund = userWalletService.refund(refundVo);
        return baseMapper.deleteById(id)>0;
    }


}
